import request from 'request';
import config from "../config/index.js";

const createRequest = (url, requestConfig, ctx, method = "GET") => {
  console.log('请求参数', requestConfig);
  let fullUrl = `${config.serviceProxy}${url}`;

  let params = '';

  let options = {
    method,
    url: fullUrl,
    headers: {
      "cookie": `csrftoken=${ctx.cookies.get('csrftoken')}; sessionid=${ctx.cookies.get('sessionid')}`,
      "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
    }
  }

  if(Array.isArray(requestConfig)){
    params = JSON.stringify(requestConfig)
  } else {
    Object.keys(requestConfig).map(item => {
      params +=`${item}=${requestConfig[item]}&`
    })
  }
 
  if (method === "GET") {
    const arr = [];
    Object.keys(requestConfig).map((key, index) => {
      arr.push(`${key}=${requestConfig[key]}`);
    })
    if (arr.length) {
      fullUrl += `?${arr.join('&')}`
    }
  } else {
    options = {
      ...options,
      body: params
    }
  }

  console.log('请求url', fullUrl);
  console.log('options', options)

  return new Promise((resolve, reject) => {
    request(options, (error, response, data) => {
      if (!error && response.statusCode === 200) {
        console.log(`返回数据：${data}`);
        resolve(data);
      } else {
        resolve({
          success: false,
          error: 1,
          code: response.statusCode,
          data: data
        });
      }
    });
  })
};

export {
  createRequest
}